<template>
  <div class="registerFrame">
    <el-card class="register-card">
      <template #header>
        <div class="card-header">
          <h2>订餐出餐系统</h2>
          <p>前台注册</p>
        </div>
      </template>

      <el-form
        :model="registerForm"
        :rules="registerRules"
        ref="registerFormRef"
        @keyup.enter="handleRegister"
      >
        <div>
          <label class="label">账号</label>
          <el-form-item prop="username">
            <el-input
              v-model="registerForm.username"
              placeholder="请输入账号(5-16位非空字符)"
              prefix-icon="User"
              clearable
              size="large"
            />
          </el-form-item>
        </div>

        <div>
          <label class="label">密码</label>
          <el-form-item prop="password">
            <el-input
              v-model="registerForm.password"
              placeholder="请输入密码(5-16位非空字符)"
              prefix-icon="Lock"
              show-password
              clearable
              size="large"
            />
          </el-form-item>
        </div>

        <div>
          <label class="label">确认密码</label>
          <el-form-item prop="confirmPassword">
            <el-input
              v-model="registerForm.confirmPassword"
              placeholder="请再次输入密码"
              prefix-icon="Lock"
              show-password
              clearable
              size="large"
            />
          </el-form-item>
        </div>

        <div>
          <label class="label">安全问题</label>
          <el-form-item prop="securityQuestion">
            <el-select
              v-model="registerForm.securityQuestion"
              placeholder="请选择安全问题"
              style="width: 100%"
              size="large"
            >
              <el-option
                v-for="item in securityQuestions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </div>

        <div>
          <label class="label">安全问题答案</label>
          <el-form-item prop="securityAnswer">
            <el-input
              v-model="registerForm.securityAnswer"
              placeholder="请输入安全问题答案"
              prefix-icon="ChatDotRound"
              clearable
              size="large"
            />
          </el-form-item>
        </div>

        <el-form-item>
          <el-button
            type="primary"
            @click="handleRegister"
            :loading="loading"
            style="width: 100%; margin-top: 20px"
            size="large"
          >
            注册
          </el-button>
        </el-form-item>
      </el-form>

      <div class="footer">
        <el-link type="primary" underline="never" @click="goToLogin" class="footer-link">
          已有账号?去登录
        </el-link>
      </div>
    </el-card>
  </div>
</template>

<script lang="js" setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import router from '@/router'
import axios from 'axios'

// 安全问题选项
const securityQuestions = [
  { value: '您母亲的姓名是什么？', label: '您母亲的姓名是什么？' },
  { value: '您父亲的姓名是什么？', label: '您父亲的姓名是什么？' },
  { value: '您的出生地是哪里？', label: '您的出生地是哪里？' },
  { value: '您的小学校名是什么？', label: '您的小学校名是什么？' },
  { value: '您的第一只宠物的名字是什么？', label: '您的第一只宠物的名字是什么？' }
]

// 注册表单数据
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  securityQuestion: '',
  securityAnswer: ''
})

// 表单验证规则
const registerRules = reactive({
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { 
      pattern: /^\S{5,16}$/,
      message: '长度在5到16个字符且不能包含空格', 
      trigger: 'blur' 
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { 
      pattern: /^\S{5,16}$/,
      message: '长度在5到16个字符且不能包含空格', 
      trigger: 'blur' 
    },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.confirmPassword && registerForm.confirmPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  securityQuestion: [
    { required: true, message: '请选择安全问题', trigger: 'change' }
  ],
  securityAnswer: [
    { required: true, message: '请输入安全问题答案', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在2到30个字符', trigger: 'blur' }
  ]
})

const loading = ref(false)
const registerFormRef = ref()

// 注册方法
const handleRegister = async () => {
  try {
    // 验证表单
    const valid = await registerFormRef.value.validate()
    if (!valid) return
    
    loading.value = true
    
    // 使用URLSearchParams构造表单数据
    const formData = new URLSearchParams()
    formData.append('username', registerForm.username)
    formData.append('password', registerForm.password)
    formData.append('securityQuestion', registerForm.securityQuestion)
    formData.append('securityAnswer', registerForm.securityAnswer)

    const response = await axios.post('http://localhost:8081/user/register', formData, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
    
    if (response.data && response.data.code === 200) {
      ElMessage.success('注册成功')
      router.push('/front/login')
    } else {
      ElMessage.error(response.data.msg || '注册失败')
    }
  } catch (error) {
    handleError(error)
  } finally {
    loading.value = false
  }
}

// 错误处理函数
const handleError = (error) => {
  if (error.response) {
    const res = error.response
    if (res.status === 400) {
      const msg = res.data.msg || '请求参数错误，请检查输入'
      ElMessage.error(msg)
    } else {
      ElMessage.error(`请求错误: ${res.status} ${res.statusText}`)
    }
    console.error('错误详情:', res.data)
  } else if (error.request) {
    ElMessage.error('网络错误，请检查网络连接')
  } else {
    ElMessage.error('请求出错: ' + error.message)
  }
}

// 跳转到登录页
const goToLogin = () => {
  router.push('/front/login')
}
</script>

<style scoped>
.registerFrame {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  min-height: 100vh;
  padding: 16px;
  background-color: #f5f7fa;
  background-image: linear-gradient(120deg, #fdfbfb 0%, #ebedee 100%);
  box-sizing: border-box;
}

.register-card {
  width: 100%;
  max-width: 450px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  margin-top: 20px;
}

.card-header {
  text-align: center;
  padding: 16px 0;
}

.card-header h2 {
  margin-bottom: 8px;
  color: #409eff;
  font-size: 24px;
}

.card-header p {
  margin: 0;
  color: #909399;
  font-size: 16px;
}

.footer {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

.footer-link {
  font-size: 15px;
  padding: 10px 0;
}

.label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #606266;
}

/* 移动端优化 */
@media (max-width: 480px) {
  .register-card {
    border-radius: 0;
    box-shadow: none;
    border: none;
    background: transparent;
    margin-top: 10px;
  }
  
  .card-header h2 {
    font-size: 22px;
  }
  
  .card-header p {
    font-size: 15px;
  }
  
  :deep(.el-input__wrapper) {
    padding: 4px 15px;
    height: 48px;
  }
  
  :deep(.el-button) {
    height: 48px;
    font-size: 16px;
  }
  
  :deep(.el-select .el-input__wrapper) {
    height: 48px;
  }
  
  .el-form-item {
    margin-bottom: 16px;
  }
}

/* 防止移动端键盘弹出时页面变形 */
@media (max-height: 600px) {
  .registerFrame {
    align-items: flex-start;
    padding-top: 10px;
  }
  
  .register-card {
    margin-top: 0;
  }
}
</style>